package com.tim.third;

import com.tim.util.FileUtils;
import org.springframework.boot.env.YamlPropertySourceLoader;
import org.springframework.core.env.PropertySource;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;

import java.io.*;
import java.util.List;
import java.util.Map;
/**
 * yml读写
 * snakeyaml
 */
public class YmlUtils {
    /**
     * 加载yml文件
     * @param rootName OriginTrackedMapPropertySource的key，不可为空串
     * @param loc
     * @return yml文件使用"---"隔开为多个yml时，返回多个元素的List
     * @throws FileNotFoundException
     * @throws IOException
     */
    public static List<PropertySource<?>> loadYml(String rootName, String loc) throws FileNotFoundException, IOException {
        return new YamlPropertySourceLoader()
                .load(rootName, FileUtils.getResource(loc));
    }

    public static Map<String,Object> loadYml(String path) throws FileNotFoundException {
        InputStream inputStream = new FileInputStream(path);
        return loadYml(inputStream);
    }

    public static Map<String, Object> loadYml(InputStream inputStream) {
        Map<String,Object> map = new Yaml().load(inputStream);
        return map;
    }

    public void saveYml(Map map, String path) throws IOException {
        DumperOptions dumperOptions = new DumperOptions();
        dumperOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);//给yml设置一个格式
        Yaml writerYaml = new Yaml(dumperOptions);
        try (FileWriter fileWriter = new FileWriter(new File(path))){
            writerYaml.dump(map,fileWriter);
        }catch (Exception e){
            e.printStackTrace();
        }

    }
}
